package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.BaseJob;
import ysq.xyg.model.info.BaseJobInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.BaseJobService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.SchedulerUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

/**
 * 定时任务
 *
 * @author congcong tao
 * @date 2018/11/26 14:36
 */
@Controller
@RequestMapping("/baseJob")
public class BaseJobController extends BaseController {

    private static Logger log= LoggerFactory.getLogger(BaseJobController.class);
    @Resource
    private Scheduler scheduler;
    @Resource
    private BaseJobService baseJobService;

    private BaseJob baseJob;

    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/baseJobList");
    }

    @RequestMapping(value = "/jsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonList(BaseJob baseJob,Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<BaseJob> pageInfo = baseJobService.pageInfo(baseJob, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (BaseJob item : pageInfo.getList()) {
                row=new JSONObject();
                row.put("id",item.getId());
                row.put("jobName",item.getJobName());
                row.put("jobGroup",item.getJobGroup());
                row.put("className",item.getClassName());
                row.put("cronExpression",item.getCronExpression());
                row.put("status",item.getStatus());
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/selectEntity",method = RequestMethod.GET)
    public ModelAndView selectEntity(String id){
        ModelAndView view = new ModelAndView("/baseJobUpdateOrSave");
        baseJob = baseJobService.selectByPrimaryKey(id);
        view.addObject("baseJob", baseJob);
        return view;
    }

    @RequestMapping(value = "/updateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateOrAddEntity(BaseJobInfo baseJobInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(baseJobInfo.getId())) {
            baseJob = new BaseJob();
            baseJob.setId(BaseUtil.uId());
            baseJob.setJobName(baseJobInfo.getJobName());
            baseJob.setJobGroup(baseJobInfo.getJobGroup());
            baseJob.setClassName(baseJobInfo.getClassName());
            baseJob.setCronExpression(baseJobInfo.getCronExpression());
            baseJob.setStatus(BaseConstant.SchedulerStatus.NORMAL.getValue());
            int id = baseJobService.insert(baseJob);
            if(id <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_INSERT);
            } else {
                SchedulerUtils.createScheduleJob(baseJob, scheduler);
            }
        } else {
            baseJob = baseJobService.selectByPrimaryKey(baseJobInfo.getId());
            baseJob.setJobName(baseJobInfo.getJobName());
            baseJob.setJobGroup(baseJobInfo.getJobGroup());
            baseJob.setClassName(baseJobInfo.getClassName());
            baseJob.setCronExpression(baseJobInfo.getCronExpression());
            int id = baseJobService.updateByPrimaryKeySelective(baseJob);
            if (id <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, baseJob);
            }
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/resumeJob",method = RequestMethod.GET)
    public @ResponseBody JSONObject resumeJob(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            baseJob = baseJobService.selectByPrimaryKey(id);
            baseJob.setStatus(BaseConstant.SchedulerStatus.NORMAL.getValue());
            int info = baseJobService.updateByPrimaryKey(baseJob);
            if (info <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SchedulerUtils.resumeJob(scheduler, baseJob.getJobName(), baseJob.getJobGroup());
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/pauseJob",method = RequestMethod.GET)
    public @ResponseBody JSONObject pauseJob(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            baseJob = baseJobService.selectByPrimaryKey(id);
            baseJob.setStatus(BaseConstant.SchedulerStatus.PAUSE.getValue());
            int info = baseJobService.updateByPrimaryKey(baseJob);
            if (info <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SchedulerUtils.pauseJob(scheduler, baseJob.getJobName(), baseJob.getJobGroup());
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/run",method = RequestMethod.GET)
    public @ResponseBody JSONObject run(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            BaseJob jobRecord = baseJobService.selectByPrimaryKey(id);
            SchedulerUtils.runOne(scheduler, jobRecord);
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/deleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject deleteEntity(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            int ids = baseJobService.deleteByPrimaryKey(id);
            if(ids <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            } else {
                BaseJob jobRecord = baseJobService.selectByPrimaryKey(id);
                SchedulerUtils.deleteJob(scheduler, jobRecord.getJobName(), jobRecord.getJobGroup());
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
}
